package com.wecahr.wecharpay.controller;

import com.wecahr.wecharpay.base.MD5Util;
import com.wecahr.wecharpay.pay.WXMyConfigUtil;
import com.wecahr.wecharpay.service.testServerice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@RestController
public class testController {


    @Autowired
    testServerice testServerice;

    private static Logger log = LoggerFactory.getLogger(testController.class);

    /**
     * @param out_trade_no      订单号
     * @param total_fee         标价金额
     * @param openid            用户的openid
     * @param spbill_create_ip  发起支付的真实ip地址
     * @param body              商品描述
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/pay", method = {RequestMethod.GET, RequestMethod.POST})
    public String orderPay(String out_trade_no,String total_fee,String openid,String spbill_create_ip,String body) throws Exception {
        log.info("进入微信支付申请");


        WXMyConfigUtil config = new WXMyConfigUtil();

        //生成预支付的订单
        Map<String,String> result = testServerice.dounifiedOrder(out_trade_no,total_fee,spbill_create_ip,body,openid);
        String nonce_str = result.get("nonce_str");
        String prepay_id = result.get("prepay_id");

        //创建的订单的时间
        Long time =System.currentTimeMillis()/1000;
        //讲创建订单的时间转化为秒
        String timestamp=time.toString();

        //签名生成算法
        MD5Util md5Util = new MD5Util();
        Map<String,String> map = new HashMap<>();
        map.put("appid",config.getAppID());
        map.put("partnerid",config.getMchID());
        map.put("package","Sign=WXPay");
        map.put("noncestr",nonce_str);
        map.put("timestamp",timestamp);
        map.put("prepayid",prepay_id);
        String sign = md5Util.getSign(map);

        String resultString="{\"appid\":\""+config.getAppID()+"\",\"partnerid\":\""+config.getMchID()+"\",\"package\":\"Sign=WXPay\"," +
                "\"noncestr\":\""+nonce_str+"\",\"timestamp\":"+timestamp+"," +
                "\"prepayid\":\""+prepay_id+"\",\"sign\":\""+sign+"\"}";
        System.err.println(resultString);

        return resultString;    //给前端app返回此字符串，再调用前端的微信sdk引起微信支付

    }


    /**
     * 订单支付异步通知
     */
    // "手机订单支付完成后回调")
    @RequestMapping(value = "/notify",method = {RequestMethod.GET, RequestMethod.POST})
    public String WXPayBack(HttpServletRequest request,HttpServletResponse response){
        String resXml="";
        System.err.println("进入异步通知");
        try{
            //
            InputStream is = request.getInputStream();
            //将InputStream转换成String
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            resXml=sb.toString();
            System.err.println(resXml);
            String result = testServerice.payBack(resXml);
//            return "<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>";
            return result;
        }catch (Exception e){
            log.error("手机支付回调通知失败",e);
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return result;
        }
    }

}
